import 'package:async/async.dart';
import 'package:bai_le_men_im/cmomon/global.dart';
import 'package:bai_le_men_im/cmomon/utils.dart';
import 'package:bai_le_men_im/conversation/chooseFriends.dart';
import 'package:bai_le_men_im/pages/search/keywordsInMessage.dart';
import 'package:bai_le_men_im/pages/setGroupName.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_wildfire/flutter_wildfire.dart';
import '../constants.dart';
import '../models/index.dart';

class ConversationGroupDetailPage extends StatefulWidget {
  Group groupInfo;
  final Function clearMessagesHandler;
  ConversationGroupDetailPage({this.groupInfo, this.clearMessagesHandler});
  @override
  _ConversationDetailPageState createState() => _ConversationDetailPageState();
}

class _ConversationDetailPageState extends State<ConversationGroupDetailPage> {
  final AsyncMemoizer _memoizer = AsyncMemoizer();
  String targetType;
  String target;
  bool _isTop = false;
  bool _isSilent = false;

  setConversationTop(bool newValue) async {
    await FlutterWildfire.setConversationTop(targetType, target, 0, newValue);
    setState(() {
      _isTop = newValue;
    });
  }

  setConversationSilent(bool newValue) async {
    await FlutterWildfire.setConversationSilent(
        targetType, target, 0, newValue);
    setState(() {
      _isSilent = newValue;
    });
  }

  getConversationInfo() async {
    var result = await FlutterWildfire.getConversation(targetType, target, 0);
    print(result);
    _isSilent = result['isSilent'];
    _isTop = result['isTop'];
  }

  String type;

  
  @override
  initState() {
    super.initState();
    targetType = 'Group';
    target = widget.groupInfo.target;
    getConversationInfo();
  }

  getMembers() {
    // TODO： 在本群的昵称
    return _memoizer.runOnce(() async {
      // await Future.delayed(Duration(milliseconds: 300));
      // Group group = Group.fromJson(await FlutterWildfire.getGroupInfo(widget.groupInfo.target));
      // widget.groupInfo = group;
      var result =
          await FlutterWildfire.getGroupMembers(widget.groupInfo.target);
      List<String> userIds = [];
      for (var item in result) {
        if (item["memberId"] == Global.profile.user.uid) {
          type = item["type"];
        }
        userIds.add(item["memberId"]);
      }
      var membersResult =
          await FlutterWildfire.getUserInfos(widget.groupInfo.target, userIds);
      List<User> members = List<User>();
      if (membersResult == null) return [];
      widget.groupInfo.memberCount = membersResult.length;
      for (var item in membersResult) {
        members.add(User.fromJson(item));
      }

      return members;
    });
  }

  showDeleteGroupMenu() async {
    return showCupertinoModalPopup<void>(
      context: context,
      builder: (BuildContext context) {
        return CupertinoActionSheet(
          title: Text('退出后不会再接收此群聊消息'),
          actions: <Widget>[
            CupertinoActionSheetAction(
              isDestructiveAction: true,
              child: Text('确定'),
              onPressed: () async {
                // Navigator.of(context).pop();
                try {
                  if (widget.clearMessagesHandler != null) {
                    await widget.clearMessagesHandler();
                  }
                  if (widget.groupInfo.owner == Global.profile.user.uid) {
                    await FlutterWildfire.dismissGroup(
                        widget.groupInfo.target, [0]);
                  } else {
                    await FlutterWildfire.quitGroup(
                        widget.groupInfo.target, [0]);
                  }
                } catch (e) {} finally {
                  Navigator.of(context).pop();
                  Navigator.of(context).pop();
                  Navigator.of(context).pop();
                }
                // Navigator.of(context).pop();
              },
            ),
          ],
          cancelButton: CupertinoActionSheetAction(
            isDefaultAction: true,
            child: Text('取消'),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
        );
      },
    );
  }

  showClearMessageMenu() async {
    return showCupertinoModalPopup<void>(
      context: context,
      builder: (BuildContext context) {
        return CupertinoActionSheet(
          actions: <Widget>[
            CupertinoActionSheetAction(
              isDestructiveAction: true,
              child: Text('清空聊天记录'),
              onPressed: () async {
                if (widget.clearMessagesHandler != null) {
                  await widget.clearMessagesHandler();
                  Navigator.of(context).pop();
                }
              },
            ),
          ],
          cancelButton: CupertinoActionSheetAction(
            isDefaultAction: true,
            child: Text('取消'),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    bool _isOwner;
    if (widget.groupInfo.owner == Global.profile.user.uid) {
      _isOwner = true;
    } else {
      _isOwner = false;
    }
    return Scaffold(
      appBar: AppBar(
        iconTheme: Theme.of(context).iconTheme,
        elevation: 0.0,
        centerTitle: true,
        title: Text(
          '聊天信息(${widget.groupInfo.memberCount})',
          style: TextStyle(color: Colors.black87),
        ),
      ),
      body: ListView(children: <Widget>[
        Padding(
          padding: const EdgeInsets.all(15.0),
          child: FutureBuilder(
              future: getMembers(),
              builder: (context, snapshot) {
                if (!snapshot.hasData) {
                  return Container(
                    child: Center(
                      child: SizedBox(
                        width: 40.0,
                        height: 40.0,
                        child: CircularProgressIndicator(),
                      ),
                    ),
                  );
                }
                return Wrap(
                  // crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    ...(snapshot.data.map((User user) {
                      return Container(
                          margin: EdgeInsets.only(right: 20.0, bottom: 10.0),
                          child: Column(
                            children: <Widget>[
                              ClipRRect(
                                borderRadius: BorderRadius.circular(
                                    Constants.AvatarRadius),
                                child: myAvatar(user.portrait, size: 50.0),
                              ),
                              SizedBox(
                                height: 5.0,
                              ),
                              SizedBox(
                                width: 40.0,
                                child: Text(
                                  user.displayName,
                                  overflow: TextOverflow.ellipsis,
                                  textAlign: TextAlign.center,
                                  style: TextStyle(fontSize: 12.0),
                                ),
                              )
                            ],
                          ));
                    }).toList()),
                    InkWell(
                      onTap: () async {
                        print(snapshot.data);

                        await Navigator.of(context)
                            .push(new MaterialPageRoute(builder: (context) {
                          return ChooseFriendPage(
                              excludeUsers: snapshot.data,
                              group: widget.groupInfo);
                        }));
                      },
                      child: Container(
                        width: 50.0,
                        height: 50.0,
                        decoration: BoxDecoration(
                            borderRadius:
                                BorderRadius.all(Radius.circular(5.0)),
                            border: Border.all(
                              color: Colors.grey[500],
                              width: 1.0,
                            )),
                        alignment: Alignment(0.0, 0.0),
                        child: Icon(
                          Icons.add,
                          color: Colors.grey[500],
                          size: 30.0,
                        ),
                      ),
                    )
                  ],
                );
              }),
        ),
        SizedBox(
          height: 10.0,
          child: Container(
            color: Colors.grey[300],
          ),
        ),
        ListTile(
          onTap: () {
            Navigator.of(context)
                .push(new MaterialPageRoute(builder: (context) {
              return SetGroupNamePage(
                group: widget.groupInfo,
              );
            }));
          },
          title: Text('群聊名称'),
          trailing: trailWidget(
              Container(
                width: 170.0,
                child: Text(
                  widget.groupInfo.name,
                  textAlign: TextAlign.right,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              width: 200.0),
        ),
        Divider(
          height: 0.0,
        ),
        ListTile(
          onTap: () async {
            await Navigator.of(context)
                .push(new MaterialPageRoute(builder: (context) {
              return SearchKeywordInConversation(targetObj: widget.groupInfo);
            }));
          },
          title: Text('查找聊天内容'),
          trailing: Icon(Icons.chevron_right),
        ),
        Divider(
          height: 0.0,
        ),
        SizedBox(
          height: 10.0,
          child: Container(
            color: Colors.grey[300],
          ),
        ),
        (_isSilent is bool) ? ListTile(
          title: Text('消息免打扰'),
          trailing: CupertinoSwitch(
              value: _isSilent, onChanged: setConversationSilent),
        ) : Container() ,
        Padding(
          padding: EdgeInsets.only(left: 20.0),
          child: Divider(
            height: 0.0,
          ),
        ),
        (_isTop is bool) ? 
        ListTile(
          title: Text('聊天置顶'),
          trailing:
              CupertinoSwitch(value: _isTop, onChanged: setConversationTop),
        ) : Container(),
        Divider(
          height: 0.0,
        ),
        SizedBox(
          height: 10.0,
          child: Container(
            color: Colors.grey[300],
          ),
        ),
        InkWell(
            onTap: showClearMessageMenu,
            child: Container(
              padding: const EdgeInsets.symmetric(
                vertical: 15.0,
              ),
              child: Center(
                child: Text(
                  '清空聊天记录',
                  style: TextStyle(color: Colors.redAccent, fontSize: 16.0),
                ),
              ),
            )),
        Padding(
          padding: const EdgeInsets.only(left: 15.0),
          child: Divider(
            height: 0.0,
          ),
        ),
        InkWell(
            onTap: showDeleteGroupMenu,
            child: Container(
              padding: const EdgeInsets.symmetric(
                vertical: 15.0,
              ),
              child: Center(
                child: Text(
                  '${_isOwner ? '解散' : '退出'}并删除',
                  style: TextStyle(color: Colors.redAccent, fontSize: 16.0),
                ),
              ),
            )),
        // Expanded(
        //   child: Container(
        //     color: Colors.grey[300],
        //   ),
        // ),
        Divider(
          height: 0.0,
        ),
        SizedBox(
          height: 10.0,
          child: Container(
            color: Colors.grey[300],
          ),
        ),
      ]),
    );
  }
}
